#include <iostream>
#include <thread>
#include <mutex>


using namespace std;

mutex m;

void fun1(int a)
{
    //初始化g1,给他了赋值了一个暂时还没上锁的mutex
    unique_lock<mutex> g1(m,defer_lock);
    cout <<"fun1 开始拉"<<endl;
    //注意手动枷锁
    g1.lock();
    cout<<"fun1函数开始打印干活"<<endl;
    cout<<"1---------------------------"<<endl;
    this_thread::sleep_for(chrono::seconds(1));
    cout<<"1---------------------------"<<endl;
    this_thread::sleep_for(chrono::seconds(1));
    cout<<"1---------------------------"<<endl;
    this_thread::sleep_for(chrono::seconds(1));
    cout<<"1---------------------------"<<endl;
    this_thread::sleep_for(chrono::seconds(1));
    g1.unlock();
    cout<<"fun1解锁"<<endl;
    this_thread::sleep_for(chrono::seconds(5));
    cout<<"fun1上锁"<<endl;
    g1.lock();
    cout<<"fun1函数结束干活"<<endl;
}

void fun2(int a)
{
    unique_lock<mutex> g2(m,try_to_lock);//尝试加锁，但如果没有锁定成功，会立即返回，不会阻塞在那里；

    cout<<"fun2函数开始打印干活"<<endl;
    cout<<"2---------------------------"<<endl;
    this_thread::sleep_for(chrono::seconds(1));
    cout<<"2---------------------------"<<endl;
    this_thread::sleep_for(chrono::seconds(1));
    g2.lock();
    cout<<"2---------------------------"<<endl;
    this_thread::sleep_for(chrono::seconds(1));
    cout<<"2---------------------------"<<endl;
    this_thread::sleep_for(chrono::seconds(1));
    cout<<"fun2函数结束干活"<<endl;

}

int main()
{
    int a=0;
    thread th1(fun1,a);
    thread  th2(fun2,a);
    th1.join();
    th2.join();

    return 0;
}
